package cn.edu.zut.internship.service.impl.result;

import cn.edu.zut.internship.bean.sys.Result;
import cn.edu.zut.internship.bean.sys.SysUser;
import cn.edu.zut.internship.iservice.notify.NotifySV;
import cn.edu.zut.internship.iservice.result.ResultSV;
import cn.edu.zut.internship.mapper.report.ReportMapper;
import cn.edu.zut.internship.mapper.result.ResultMapper;
import cn.edu.zut.internship.mapper.setting.SettingMapper;
import cn.edu.zut.internship.utils.ExcelUtils;
import cn.edu.zut.internship.utils.FileNameUtil;
import cn.edu.zut.internship.utils.PrimaryKeyUtil;
import cn.edu.zut.internship.utils.ThreadPoolUtil;
import com.alibaba.dubbo.config.annotation.Service;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class ResultSVImpl implements ResultSV {
    @Autowired
    ResultMapper resultMapper;
    @Autowired
    PrimaryKeyUtil primaryKeyUtil;
    @Autowired
    ReportMapper reportMapper;
    @Autowired
    NotifySV notifySV;
    @Autowired
    SettingMapper settingMapper;
    @Override
    public Result getMyResultList(Map params) {
        Result result = new Result();
        List<Map> myResultList = resultMapper.getMyResultList(params);
        int total = resultMapper.getMyResultListCount(params);
        result.setBeans(myResultList);
        result.getBean().put("total",total);
        return result;
    }

    @Override
    public Result getMyResult(Map params) {
        Result result = new Result();
        Map myResult = resultMapper.getMyResult(params);
        if(!CollectionUtils.isEmpty(myResult)) {
            //处理总成绩
            BigDecimal peacetimeResultRatio = new BigDecimal((String) settingMapper.getSetting("peacetimeResult").get("settingValue"));
            BigDecimal centreResultRatio = new BigDecimal((String) settingMapper.getSetting("centreResult").get("settingValue"));
            BigDecimal finalResultRatio = new BigDecimal((String) settingMapper.getSetting("finalResult").get("settingValue"));
            BigDecimal chu = new BigDecimal("100");
            BigDecimal peacetimeResult = (BigDecimal) myResult.get("peacetimeResult");
            BigDecimal finalResult = new BigDecimal((Long) myResult.get("finalResult"));
            BigDecimal centreResult = new BigDecimal((Long) myResult.get("centreResult"));
            BigDecimal sumResult = peacetimeResult.multiply(peacetimeResultRatio).divide(chu, 2, BigDecimal.ROUND_HALF_UP).add(finalResult.multiply(finalResultRatio).divide(chu, 2, BigDecimal.ROUND_HALF_UP)).add(centreResult.multiply(centreResultRatio).divide(chu, 2, BigDecimal.ROUND_HALF_UP));
            myResult.put("sumResult", sumResult);
        }else{
            myResult = new HashMap();
            myResult.put("peacetimeResult",0);
            myResult.put("centreResult",0);
            myResult.put("finalResult",0);
            myResult.put("sumResult",0);
        }
        result.setBean(myResult);
        return result;
    }

    @Override
    public Result reportResult(Map params) {
        Result result = new Result();
        //修改报告状态
        Map map = new HashMap();
        map.put("reportStatus",1);
        map.put("reportId",params.get("reportId"));
        reportMapper.updateReport(map);
        //存入成绩表
        int reportType = (int) params.get("reportType");
        if(reportType==0||reportType==1){
            params.put("resultType", 0);
        }else if(reportType==2){
            params.put("resultType", 1);
        }else if(reportType == 3){
            params.put("resultType", 2);
        }
        Long resultId = primaryKeyUtil.generatePrimaryKey("result");
        params.put("resultId", resultId);
        resultMapper.reportResult(params);
        return result;
    }

    @Override
    public Result selectRsultList(Map params) {
        Result result = new Result();
        //获取当前学期，只查询当前学期的数据
        Map semester = settingMapper.getSetting("currentSemester");
        String nowSemester = (String) semester.get("settingValue");
        params.put("semester",nowSemester);
        SysUser userInfo = (SysUser) params.get("userInfo");
        int userType = userInfo.getUserType();
        List<Map> resultList = new ArrayList<>();
        if(userType==0){//管理员
            resultList = resultMapper.getResultList(params);
            int total = ((Long) resultMapper.getResultListCount(params).get("total")).intValue();
            result.setBeans(resultList);
            result.getBean().put("total",total);
        }else if(userType==1){//教师
            params.put("teachAccount",userInfo.getUserAccount());
            resultList = resultMapper.getTSResultList(params);
            int total = ((Long) resultMapper.getTSResultListCount(params).get("total")).intValue();
            result.setBeans(resultList);
            result.getBean().put("total",total);
        }

        BigDecimal peacetimeResultRatio = new BigDecimal((String)settingMapper.getSetting("peacetimeResult").get("settingValue"));
        BigDecimal centreResultRatio =new BigDecimal((String)settingMapper.getSetting("centreResult").get("settingValue"));
        BigDecimal finalResultRatio = new BigDecimal((String)settingMapper.getSetting("finalResult").get("settingValue"));
        BigDecimal chu = new BigDecimal("100");
        //处理总成绩
        for(Map map:resultList){
            BigDecimal peacetimeResult = (BigDecimal) map.get("peacetimeResult");
            BigDecimal finalResult = new BigDecimal((Long) map.get("finalResult"));
            BigDecimal centreResult = new BigDecimal((Long) map.get("centreResult"));
            BigDecimal sumResult = peacetimeResult.multiply(peacetimeResultRatio).divide(chu,2,BigDecimal.ROUND_HALF_UP).add(finalResult.multiply(finalResultRatio).divide(chu,2,BigDecimal.ROUND_HALF_UP)).add(centreResult.multiply(centreResultRatio).divide(chu,2,BigDecimal.ROUND_HALF_UP));
            map.put("sumResult",sumResult);
        }
        return result;
    }

    @Override
    public Result exportResult(Map params) {
        Result result = new Result();
        SysUser userInfo = (SysUser) params.get("userInfo");
        //开启线程启动导出程序
        int userType = userInfo.getUserType();
        if(userType==0){//管理员
            ThreadPoolUtil.getThreadPool().execute(new taskA(params));
        }else if(userType==1){//教师
            params.put("teachAccount",userInfo.getUserAccount());
            ThreadPoolUtil.getThreadPool().execute(new taskB(params));
        }
        //返回导出任务执行成功
      ///  int userType = userInfo.getUserType();
        if(userType==0){
            result.getBean().put("excel","后台正在导出");
        }else if(userType==1){
            result.getBean().put("excel","后台正在导出");
        }
        return result;
    }
    @Override
    public Result getReportResult(Map params) {
        Result result = new Result();
        Map reportResult = resultMapper.getReportResult(params);
        result.setBean(reportResult);
        return result;
    }

    @Override
    public Result detail(Map params) {
        Result result = new Result();
        List<Map> detail = resultMapper.detail(params);
        for(Map map:detail){
            int reportType = (int) map.get("reportType");
            if(reportType==0){
                map.put("reportTypeName","周报");
            }else if(reportType==1){
                map.put("reportTypeName","月报");
            }else if(reportType==2){
                map.put("reportTypeName","中期报告");
            }else if(reportType==3){
                map.put("reportTypeName","实习实训论文");
            }
        }
        result.setBeans(detail);
        return result;
    }

    class taskA extends  Thread{
        private Map params;
        public taskA(Map params) {
            this.params=params;
        }
        @Override
        public void run() {
            //获取当前学期
            Map semester = settingMapper.getSetting("currentSemester");
            String nowSemester = (String) semester.get("settingValue");
            params.put("semester",nowSemester);
            SysUser userInfo = (SysUser) params.get("userInfo");
            int[] sizi = {20,20,20,20,20,20,20,20};
            String[] names = {"学号","姓名","教师姓名","平时成绩","中期检查成绩","终期检查成绩","总成绩"};
            String[] keys = {"studentAccount","studentName","teachName","peacetimeResult","centreResult","finalResult","sumResult"};
            String fileName = "成绩单_"+ FileNameUtil.getFileName()+".xlsx";
            //创建提醒消息
            Map notify = new HashMap();
            notify.put("sendAccount","admin");
            notify.put("sendType",0);
            notify.put("notifyType",4);
            notify.put("targetAccount",userInfo.getUserAccount());
            notify.put("targetType",0);
            notify.put("creatAccount",userInfo.getUserAccount());
            try {
                List<Map> resultList = resultMapper.getResultList(params);
                if (CollectionUtils.isEmpty(resultList)) {
                    notify.put("content","没有符合条件的成绩！导出失败！");
                }else{
                    //处理导出的成绩
                    BigDecimal peacetimeResultRatio = new BigDecimal((String)settingMapper.getSetting("peacetimeResult").get("settingValue"));
                    BigDecimal centreResultRatio =new BigDecimal((String)settingMapper.getSetting("centreResult").get("settingValue"));
                    BigDecimal finalResultRatio = new BigDecimal((String)settingMapper.getSetting("finalResult").get("settingValue"));
                    BigDecimal chu = new BigDecimal("100");
                    for(Map map:resultList){
                        BigDecimal peacetimeResult = (BigDecimal) map.get("peacetimeResult");
                        BigDecimal finalResult = new BigDecimal((Long) map.get("finalResult"));
                        BigDecimal centreResult = new BigDecimal((Long) map.get("centreResult"));
                        BigDecimal sumResult = peacetimeResult.multiply(peacetimeResultRatio).divide(chu,2,BigDecimal.ROUND_HALF_UP).add(finalResult.multiply(finalResultRatio).divide(chu,2,BigDecimal.ROUND_HALF_UP)).add(centreResult.multiply(centreResultRatio).divide(chu,2,BigDecimal.ROUND_HALF_UP));
                        map.put("sumResult",sumResult);
                    }
                    String fileUrl = ExcelUtils.myExportExcel(names,keys,sizi,fileName, resultList);
                    notify.put("contentUrl",fileUrl);
                    notify.put("content","你启动的成绩导出任务已执行完毕，文件下载地址为："+fileUrl);
                }
            }catch (Exception e){
                notify.put("content","你启动的成绩导出任务执行异常！请稍后再试");
            }
            //发送提醒消息
            notifySV.addNotify(notify);
        }
    }
    class taskB extends  Thread{
        private Map params;
        public taskB(Map params) {
            this.params=params;
        }
        @Override
        public void run() {
            //获取当前学期
            Map semester = settingMapper.getSetting("currentSemester");
            String nowSemester = (String) semester.get("settingValue");
            params.put("semester",nowSemester);
            SysUser userInfo = (SysUser) params.get("userInfo");
            int[] sizi = {20,20,20,20,20,20,20};
            String[] names = {"学号","姓名","教师姓名","平时成绩","中期检查成绩","终期检查成绩","总成绩"};
            String[] keys = {"studentAccount","studentName","teachName","peacetimeResult","centreResult","finalResult","sumResult"};
            String fileName = "成绩单_"+ FileNameUtil.getFileName()+".xlsx";
            //创建提醒消息
            Map notify = new HashMap();
            notify.put("sendAccount","admin");
            notify.put("sendType",0);
            notify.put("notifyType",4);
            notify.put("targetAccount",userInfo.getUserAccount());
            notify.put("targetType",0);
            notify.put("creatAccount",userInfo.getUserAccount());
            try {
                List<Map> resultList = resultMapper.getTSResultList(params);
                if (CollectionUtils.isEmpty(resultList)) {
                    notify.put("content","没有符合条件的成绩！导出失败！");
                }else{
                    //处理导出的成绩
                    BigDecimal peacetimeResultRatio = new BigDecimal((String)settingMapper.getSetting("peacetimeResult").get("settingValue"));
                    BigDecimal centreResultRatio =new BigDecimal((String)settingMapper.getSetting("centreResult").get("settingValue"));
                    BigDecimal finalResultRatio = new BigDecimal((String)settingMapper.getSetting("finalResult").get("settingValue"));
                    BigDecimal chu = new BigDecimal("100");
                    for(Map map:resultList){
                        BigDecimal peacetimeResult = (BigDecimal) map.get("peacetimeResult");
                        BigDecimal finalResult = new BigDecimal((Long) map.get("finalResult"));
                        BigDecimal centreResult = new BigDecimal((Long) map.get("centreResult"));
                        BigDecimal sumResult = peacetimeResult.multiply(peacetimeResultRatio).divide(chu,2,BigDecimal.ROUND_HALF_UP).add(finalResult.multiply(finalResultRatio).divide(chu,2,BigDecimal.ROUND_HALF_UP)).add(centreResult.multiply(centreResultRatio).divide(chu,2,BigDecimal.ROUND_HALF_UP));
                        map.put("sumResult",sumResult);
                    }
                    String fileUrl = ExcelUtils.myExportExcel(names,keys,sizi,fileName, resultList);
                    notify.put("contentUrl",fileUrl);
                    notify.put("content","你启动的成绩导出任务已执行完毕，文件下载地址为："+fileUrl);
                }
            }catch (Exception e){
                notify.put("content","你启动的成绩导出任务执行异常！请稍后再试");
            }
            //发送提醒消息
            notifySV.addNotify(notify);
        }
    }

}
